package org.itboys.mobile.service.mongo.web;


import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.TianJieWalletBlockMapper;
import org.itboys.mobile.dao.TianJieWalletMapper;
import org.itboys.mobile.dao.TianJieWalletRecordMapper;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.TianJieGroup;
import org.itboys.mobile.entity.mysql.TianJieWallet;
import org.itboys.mobile.entity.mysql.TianJieWalletBlock;
import org.itboys.mobile.entity.mysql.TianJieWalletRecord;
import org.itboys.mobile.entity.mysql.selling.TianJieSellingReward;
import org.itboys.mobile.service.mysql.web.TianJieGroupService;
import org.itboys.mobile.service.mysql.web.TianJieWalletService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：天街_金融_组织_service
 */
@Service
public class TianJieMemberService extends BaseMongoService<TianJieMember> {

    @Autowired
    private TianJieWalletService walletService;
    @Autowired
    private TianJieWalletBlockMapper walletBlockMapper;
    @Autowired
    private SystemDictionaryService dictionaryService;
    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<TianJieMember> getEntityClass() {
        return TianJieMember.class;
    }

    /**
     * 查询金融模块用户
     * @param request
     * @return
     */
    public PageResult<TianJieMember> getMember(HttpServletRequest request){
        Map<String,Object> param =new HashMap<String,Object>();

        param.put("userType",1);
        param.put("financeIsFinance", SundayCommonConstants.YES);
        Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request,"nickName","userName");
        PageResult<TianJieMember> pageResult= super.containpageQuery(request,containsparam,param);

        List<Long> memberIds = new ArrayList<>();
        for(TianJieMember member:pageResult.getData()){
            memberIds.add(member.getId());
        }
        //匹配充值金额。
        if(ListUtil.isNotNull(memberIds)){

                //查询用户的钱包
                param.clear();
                param.put("memberIds",memberIds);
                List<TianJieWallet> wallets=walletService.select(param);
                //查询用户区块链钱包
                param.clear();
                param.put("memberIds",memberIds);
                List<TianJieWalletBlock> walletBlocks=walletBlockMapper.select(param);
                //区块链钱包的卖出天数
                Integer saleDay=Integer.valueOf(dictionaryService.getDictionaryByKey2("blockSaleDay").getValue());
                for(TianJieMember member:pageResult.getData()){
                    //匹配钱包
                    for(TianJieWallet wallet:wallets){
                        if( LongUtil.isNotZreo(wallet.getMemberId())&&
                                member.getId()==wallet.getMemberId().longValue()){
                            member.setTotalAmount(wallet.getTotalAmount());
                            member.setReleaseAmount(wallet.getReleaseAmount());
                            member.setCashAmount(wallet.getCashAmount());
                            member.setProfitAmount(wallet.getProfitAmount());
                            member.setTotalAchievement(wallet.getTotalAchievement());
                            member.setWalletStatus(wallet.getStatus());
                            break;
                        }
                    }

                    for(TianJieWalletBlock walletBlock:walletBlocks){
                        if( LongUtil.isNotZreo(walletBlock.getMemberId())&&
                                member.getId()==walletBlock.getMemberId().longValue()){
                            member.setBaseAmount(walletBlock.getBaseAmount());
                            member.setAbleAmount(walletBlock.getAbleAmount());
                            member.setBlockNumber(walletBlock.getBlockNumber());
                            if(walletBlock.getSaleDay()==null){
                                member.setSaleDay(saleDay);
                            }else{
                                member.setSaleDay(walletBlock.getSaleDay());
                            }
                            break;
                        }
                    }

                }

        }
        return pageResult;
    }

    /**
     * 按用户推荐获取用户管理
     * @param request
     * @return
     */
    public List<TianJieMember> getTree(HttpServletRequest request){
        Map<String,Object> param =new HashMap<String,Object>();
        param.put("userType",1);
        param.put("financeIsFinance", SundayCommonConstants.YES);
        String nickName=request.getParameter("nickName");
        String userName=request.getParameter("userName");
        /*if(StringUtils.isNotEmpty(request.getParameter("nickName"))){
            logger.info(request.getParameter("nickName"));
            param.put("contains:nickName",StringUtils.isNotEmpty(request.getParameter("nickName")));
        }
        if(StringUtils.isNotEmpty(request.getParameter("userName"))){
            logger.info(request.getParameter("userName"));
            param.put("contains:userName",StringUtils.isNotEmpty(request.getParameter("userName")));
        }*/
        List<TianJieMember> members = super.list(param);
        //查询用户的钱包
        List<Long> memberIds = new ArrayList<>();
        for(TianJieMember member:members){
            memberIds.add(member.getId());
        }
        //匹配充值金额。
        if(ListUtil.isNotNull(memberIds)){
            param.clear();
            //查询用户的钱包
            param.put("memberIds",memberIds);
            List<TianJieWallet> wallets=walletService.select(param);

            for(TianJieMember member:members){
                for(TianJieWallet wallet:wallets){
                    if( LongUtil.isNotZreo(wallet.getMemberId())&&
                            member.getId()==wallet.getMemberId().longValue()){
                        member.setTotalAmount(wallet.getTotalAmount());
                        member.setReleaseAmount(wallet.getReleaseAmount());
                        member.setCashAmount(wallet.getCashAmount());
                        member.setProfitAmount(wallet.getProfitAmount());
                        member.setTotalAchievement(wallet.getTotalAchievement());
                        member.setWalletStatus(wallet.getStatus());
                        break;
                    }
                }
              //  member.setChargeAmount(new BigDecimal(chargeAmount));
                // member.setPresentAmount(new BigDecimal(presentAmount));
             //   member.setAchievementAmount(new BigDecimal(achievementAmount));
             //   member.setFinanceWalletStatus(walletStatus);
            }
        }
        List<TianJieMember> parents = new ArrayList<>();
        List<TianJieMember> children = new ArrayList<>();
        for(TianJieMember member:members){
            if(LongUtil.isNotZreo(member.getFinanceTjId())){
                if(StringUtils.isNotEmpty(userName)){
                    if(member.getUserName().equalsIgnoreCase(userName)){
                        children.add(member);
                    }
                    userName=null;
                }else{
                    children.add(member);
                }


            }else{
                if(StringUtils.isNotEmpty(userName)){
                    if(member.getUserName().equalsIgnoreCase(userName)){
                        parents.add(member);
                    }
                    userName=null;
                }else{
                    parents.add(member);
                }

            }
        }

        //logger.info("推荐人--"+children.size());
        List<TianJieMember> parents2 = new ArrayList<>();
        long start=System.currentTimeMillis();
        for(TianJieMember parent:parents){
            parents2.add(getTreeData3(parent,children,userName));
        }
        long end=System.currentTimeMillis();
        logger.info("耗时--"+(end-start)+"毫秒");
     return parents2;
    }

    /**
     * 递归获取用户下级
     * @param parent
     *  @param children
     * @return
     */
    public TianJieMember getTreeData2(TianJieMember parent,List<TianJieMember> children,String userName){
                List<TianJieMember> tjMembers = new ArrayList<>();
                for(TianJieMember child:children) {
                    if(parent.getId()==child.getFinanceTjId().longValue()){
                        if(StringUtils.isNotEmpty(userName)){
                            if(child.getUserName().equalsIgnoreCase(userName)){
                                userName=null;
                                tjMembers.add(child);
                            }
                        }else{
                            tjMembers.add(child);
                        }

                    }
                    parent.setChildren(tjMembers);
                    if(ListUtil.isNotNull(tjMembers)){
                        //logger.info("推荐人-=="+tjMembers.size());
                        getTreeData2(child,children,userName);
                    }
                }

                //tjMembers.clear();
            return parent;
    }
    public TianJieMember getTreeData3(TianJieMember parent,List<TianJieMember> children,String userName){
        List<TianJieMember> tjMembers = new ArrayList<>();
        for(TianJieMember child:children) {
            if(parent.getId()==child.getFinanceTjId().longValue()){
                if(StringUtils.isNotEmpty(userName)){
                    if(child.getUserName().equalsIgnoreCase(userName)){
                        tjMembers.add(child);
                    }
                }else{
                    tjMembers.add(child);
                }
              //  tjMembers.add(child);
            }

            parent.setChildren(tjMembers);
        }

        if(ListUtil.isNotNull(tjMembers)){
            //logger.info("推荐人-=="+tjMembers.size());
            for(TianJieMember tjMember:tjMembers){
                getTreeData2(tjMember,children,userName);
            }
        }
        //tjMembers.clear();
        return parent;
    }
    /**
     * 查询单个用户详情
     * @param memberId
     * @return
     */
    public TianJieMember findOne(long memberId){
        return super.getById(memberId);
    }



    /**
     * 修改用户钱包状态
     * @param memberId
     */
    public void changeStatus(long memberId,Integer status){

        TianJieWallet wallet = walletService.findByMemberId(memberId);
        wallet.setStatus(status);
        walletService.update(wallet);
    }


}
